package com.easy;

import com.easy.proxy.CGLibMethodInterceptor;
import com.easy.proxy.DynamicProxy;
import com.easy.proxy.JdkInvocationHandler;
import com.easy.service.AliSmsService;
import com.easy.service.Shopping;
import com.easy.service.ShoppingImpl;
import net.sf.cglib.proxy.Enhancer;
import org.junit.Test;

import java.lang.reflect.Proxy;

public class test {
    //测试静态代理
    @Test
    public void testProxy() {
        Shopping shopping = new ShoppingImpl();
        com.easy.proxy.Proxy proxy = new com.easy.proxy.Proxy(shopping);
        proxy.buyWawa("王二狗");
    }

    //测试动态代理
    @Test
    public void testDynamicProxy() {
        Shopping shopping = new ShoppingImpl();
        DynamicProxy dynamicProxy = new DynamicProxy(shopping);
        Shopping proxyShopping = (Shopping) dynamicProxy.getObject();
        proxyShopping.buyWawa("王二狗");
        //动态代理的实现原理
        //在调用Proxy.newProxyInstance 方法时，会生成一个名为$Proxy0的类,该类继承了Porxy,实现了传入的接口
        //在每一个方法的调用处,都会调用this.h.invoke 方法,而h对象则为传入的实现了InvocationHandler 的类(DynamicProxy)
        //调用该对象的invoke 方法,就实现了动态代理的整个过程
    }

    @Test
    public void jdkDynamicProxy() {
        Shopping shopping = new ShoppingImpl();
        //获取代理类
        Shopping proxyInstance = (Shopping) Proxy.newProxyInstance(
                //类加载器
                shopping.getClass().getClassLoader(),
                //代理类要实现的接口
                shopping.getClass().getInterfaces(),
                //代理对象对应的自定义InvocationHandler
                new JdkInvocationHandler(shopping));
        proxyInstance.buyWawa("刘二狗");
    }

    @Test
    public void cglibDynamicProxy() {
        //获取代理类
        Enhancer enhancer = new Enhancer();
        //设置类加载器
        enhancer.setClassLoader(AliSmsService.class.getClassLoader());
        //设置被代理类
        enhancer.setSuperclass(AliSmsService.class);
        //设置方法拦截器
        enhancer.setCallback(new CGLibMethodInterceptor());
        //创建代理类
        AliSmsService aliSmsService = (AliSmsService) enhancer.create();
        aliSmsService.send("CGLIB");
    }
}
